package com.css.common.core.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.security.MessageDigest;
import java.util.Arrays;

public class WXPublicUtils {

    private static final Logger logger = LoggerFactory.getLogger(WXPublicUtils.class);

    private static String token = "zhongruanyunqi";

    public static boolean verifyUrl(String msgSignature, String timeStamp, String nonce)
            throws Exception {
        String signature = getSHA1(token, timeStamp, nonce);
        if (!signature.equals(msgSignature)) {
            throw new Exception("token验证失败");
        }
        return true;
    }


    public static String getSHA1(String token, String timestamp, String nonce) throws Exception {
        try {
            String[] array = new String[]{token, timestamp, nonce};
            StringBuffer sb = new StringBuffer();
            // 字符串排序
            Arrays.sort(array);
            for (int i = 0; i < 3; i++) {
                sb.append(array[i]);
            }
            String str = sb.toString();
            // SHA1签名生成
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            md.update(str.getBytes());
            byte[] digest = md.digest();

            StringBuffer hexstr = new StringBuffer();
            String shaHex = "";
            for (int i = 0; i < digest.length; i++) {
                shaHex = Integer.toHexString(digest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexstr.append(0);
                }
                hexstr.append(shaHex);
            }
            return hexstr.toString();
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("token验证失败");
        }
    }
}
